package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.PermissionDao;
import com.itheima.dao.RoleDao;
import com.itheima.dao.UserDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 用户服务
 */
@Service(interfaceClass = UserService.class)
@Transactional
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;
    @Autowired
    private RoleDao roleDao;
    @Autowired
    private PermissionDao permissionDao;

    //根据用户名查询用户信息,包括用户的角色和角色关联的权限
    public User findByUsername(String username) {
        User user = userDao.findByUsername(username);//根据用户名查询用户表
        if(user == null){
            return null;
        }
        Integer userId = user.getId();
        //根据用户id查询关联的角色
        Set<Role> roles = roleDao.findByUserId(userId);
        if(roles != null && roles.size() > 0){
            //遍历角色集合，查询每个角色关联的权限
            for (Role role : roles) {
                Integer roleId = role.getId();//角色id
                //根据角色id查询关联的权限
                Set<Permission> permissions = permissionDao.findByRoleId(roleId);
                if(permissions != null && permissions.size() > 0){
                    //角色关联权限集合
                    role.setPermissions(permissions);
                }
            }
            //用户关联角色集合
            user.setRoles(roles);
        }

        return user;
    }

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {

        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        Page<User> page = userDao.findPage(queryPageBean.getQueryString());

        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    public List<Role> getRoles() {

        List<Role> roles = userDao.getRoles();
        return roles;
    }

    @Override
    public Boolean checkUsername(String username) {
        Integer count = userDao.checkUsername(username);
        if(count>0){
            return false;
        }
        return true;
    }

    @Override
    public void addUser(User user, Integer[] roleIds) {

        userDao.addUser(user);
        Integer userId = user.getId();
        setUserAndRole(userId,roleIds);
    }

    @Override
    public User findUserById(Integer id) {

        User userById = userDao.findUserById(id);
        return userById;
    }

    @Override
    public List<Integer>  findRoleIdsByUserId(Integer userId) {

        List<Integer>  roleIds = userDao.findRoleIdsByUserId(userId);
        return  roleIds;
    }

    @Override
    public Result editUser(User user, Integer[] roleIds) {
        Integer count = userDao.checkUsername(user.getUsername());
        if(count>0){
            User byUsername = userDao.findByUsername(user.getUsername());
            if(user.getId()!=byUsername.getId()){
                return new Result(false,"用户名已被占用");
            }
        }
        userDao.updateUser(user);
        userDao.deleteUserAndRole(user.getId());
        setUserAndRole(user.getId(),roleIds);
        return new Result(true,"编辑用户信息成功");
    }

    @Override
    public void deleteUser(Integer id) {
        userDao.deleteUserAndRole(id);
        userDao.deleteUser(id);
    }

    @Override
    public void updatePassword(Map map) {

        userDao.updatePassword(map);
    }

    public void setUserAndRole(Integer userId,Integer[] roleIds){
        if(roleIds.length>0){
            for (int i = 0; i < roleIds.length; i++) {
                Integer roleId=roleIds[i];
                Map<String, Integer> map = new HashMap<>();
                map.put("user_id",userId);
                map.put("role_id",roleId);
                userDao.addUserAndRole(map);
            }
        }
    }
}
